/**
 * 表单工具
 * Created by koal on 2018/4/27.
 */
define(['jquery', 'msgTool'], function ($, msgTool) {
	
	msgTool.options = {  
        closeButton: false,  
        debug: false,  
        progressBar: true,  
        positionClass: "toast-bottom-center",  
        onclick: null,  
        showDuration: "300",  
        hideDuration: "1000",  
        timeOut: "2000",  
        extendedTimeOut: "1000",  
        showEasing: "swing",  
        hideEasing: "linear",  
        showMethod: "fadeIn",  
        hideMethod: "fadeOut"  
    };
	
	function initFormData(data, $form){
		if(!data) return;
		$.each($form.find("input,select"), function(i, obj) {
    		var type = $(obj).attr("type");
    		var name = $(obj).attr("name");
    		if(!name) return;
    		var value = $(obj).val();
    		if(type=="text" || type=="hidden"){ 
    			$(obj).val(data[$(obj).attr("name")]);
    		}else if(type=="date"){
    			var date = new Date(data[$(obj).attr("name")]);
    			var month = (date.getMonth() + 1)< 9 ? ("0" + (date.getMonth()+1)) :  date.getMonth() + 1;
    			var day = (date.getDate() + 1)< 9 ? ("0" + date.getDate()) :  date.getDate() + 1;
    			$(obj).val(date.getFullYear() + '-' + month + '-' + day);
    		}else if(type=="radio" && data[name]==value ){
    			obj.checked = true;  
    		}else if (obj.tagName == "SELECT"){
    			$(obj).val(data[name]);
    		}else if (type=="checkbox"  ){
    			var checkBoxValue = data[name];
    			if(checkBoxValue instanceof Array){
    				$.each(checkBoxValue, function(i, v){
    					if(v == value){
    						obj.checked = true;  
    					}
    				});
    			}else{
    				if(data[name] == value){
    					obj.checked = true;  
    				}
    			}
    		}
    	});
	}
	
	
	/**
	 * 拼接Select option HTML
	 */
	function appendSelectOption($target, data, valueStr, nameStr){
		if($target && data){
			var jsonData = {};
			for(var i=0; i<data.length; ++i){
				jsonData[data[i][valueStr]] = data[i];
				$target.append("<option value='"+data[i][valueStr] +"' >"+data[i][nameStr] +"</option>")
			}
			//绑定下拉框的变更事件
			$target.on("change",function(){
				//照片显示
				if(!$(this).val())return;
				var formData = jsonData[$(this).val()];
				$("#photo").attr("src",formData.userPhoto);
				//表单赋值
				initFormData(formData,$target.parents("form"));
				$("#applyId").val(formData.id);
			});
		}
	}
	
	var uploadDefaultParameter = {
		uploadUrl: '/common/uploader/index',
		uploadExtraData: {filesType: 0},//上传图片
        showPreview: true,
        showUpload: true,
        autoReplace: true,
        showClose: false,
        showRemove: false,
        elErrorContainer: '#kartik-file-errors',
        allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg'],
        browseIcon: '<i class="iconfont icon-wenjianjia"></i>&nbsp;',
        browseClass: 'btn btn-success',//浏览样式
        uploadIcon: '<i class="iconfont icon-upload"></i>&nbsp;', //上传图标
        uploadClass: 'btn btn-info',//上传样式
        removeIcon: '<i class="iconfont icon-remove"></i>&nbsp;', //移除图标
        removeClass: 'btn btn-info', //移除样式
        fileActionSettings:{
        	 removeIcon: '<i class="iconfont icon-remove"></i>',
        	 indicatorNew: '<i class="iconfont icon-file"></i>',
        	 indicatorSuccess: '<i class="iconfont icon-file"></i>',
        	 showUpload: false,
        	 showZoom: false,
        	 showDrag: false
        }
	}

    return {
    	msgTool:msgTool,
    	/**
         * form表单转换成json
         */
    	getFormJson:function (form) {
            var data = {};
            var a = $(form).serializeArray();
            $.each(a, function () {
                if (data[this.name] !== undefined) {
                    if (!data[this.name].push) {
                        data[this.name] = [data[this.name]];
                    }
                    data[this.name].push(this.value || '');
                } else {
                    data[this.name] = this.value || '';
                }
            });
            return data;
        },
        
        /**
         * 表单赋值
         */
        initFormData:initFormData,
        /*
         * 初始化下拉框
         */
        initSelectOption:function($select, url, data){
        	$.ajax({
                url: url,
                type: 'GET',
                data: data || {},
                dataType: "JSON",
                success: function (data) {
                    if (data.success) {
                    	appendSelectOption($select, data.rows, "id", "name")
                    } else {
                    	msgTool.error(data.msg);	
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
        },
        
        
        /**
         * 上传头像
         */
        initUpload :function (){
        	$("#userImg").fileinput(uploadDefaultParameter);
        	$("#userImg").on("fileuploaded", function (event, data, previewId, index) {
    			$("#photo").attr("src","/" + data.response.url)
    			$("input[name='userPhoto']").val("/" + data.response.url)
        	})
        },
        
        initChange:function(){
        	//解决select readonly无效的问题
        	$("form").find("select").on("focus",function(){
        		this.defaultIndex=this.selectedIndex;
        	});
        	$("form").find("select").on("change",function(){
        		if(this.name){
        			this.selectedIndex=this.defaultIndex;
        		}
        	});
        	
        	//启用变更
			$(".change").on("click", function(obj){
				var input = $(obj.currentTarget).parent().prev();
				
				if($(obj.currentTarget).html() == "变更"){
					if(input[0].tagName == "SELECT"){
						$(input).off("change");
					}
					input.removeAttr("readonly");
					$(obj.currentTarget).data("default", input.val());
					$(obj.currentTarget).html("取消");
					$(obj.currentTarget).addClass("btn-danger");
				}else{
					if(input[0].tagName == "SELECT"){
						$(input).on("change",function(){
							this.selectedIndex=this.defaultIndex;
						});
					}
					$(obj.currentTarget).parent().prev().attr("readonly","readonly");
					$(obj.currentTarget).html("变更");
					$(obj.currentTarget).removeClass("btn-danger");
					input.val($(obj.currentTarget).data("default"));
				}
			});
        } ,
        sendAjax:function(){
        	//发送ajax 请求
        	$.ajax({
    			type:initParam.type || "post",
    			url:initParam.url,
    			async:initParam.async || true,
    			dataType:"json",
    			data:initParam.data,
    			contentType:initParam.contentType || "application/x-www-form-urlencoded",
    			error:function (XMLHttpRequest, textStatus, errorThrown) {},
    			success:function (data, textStatus) {
    				if(data.success){
    					initParam.callback && initParam.callback(data);
    				}else{
    					msgTool.error("服务器异常");	
    				}
    			},
    			error:function(request,msg, exception){
    				msgTool.error("接口调用错误");	
    			}
    		});
        }
    }
});
